var page = null;
window.addEvent('domready', function(){
	new SlsBo(page);
});
var SlsBo = new Class ({
	Implements: [Events, Options],
	options : {
	},
	
	initialize:function(type, options){
		this.type = type;
		switch(this.type){
			case 'edit':
				this.langSelected = null;
				this.initEdit();
				break;
			case 'login':
				this.initLogin();
				break;	
			case 'listing':
				this.initGroupBySelect();
				this.initExportSelect();
				this.initListing();
				this.initCheckAll();
				
				this.updateDeleteListing();
				this.updateEditListing();
				this.updateQuickEditListing();
				this.updateCloneListing();
				this.updateEmailListing();
				break;
			default:
				break;
		}
		this.initOpenWrappers();
		
		this.quickIFrames();
	},
	
	initCheckAll: function(){
		if (typeOf($('checkAll')) == 'element'){
			$('checkAll').addEvent('change', function(e, element){
				$$('table.listing tr td input').each(function(element, index){
					element.set('checked',($('checkAll').get('checked')) ? true : false);
				});
				this.updateDeleteListing();
				this.updateEditListing();
				this.updateQuickEditListing();
				this.updateCloneListing();
				this.updateEmailListing();
				e.stop();
			}.bind(this))
		}
	},
	
	initEdit : function(){
		$$('div.grey_wrapper_no_padding ul.langs li a').each(function(element, index){
			if (element.get('class') == 'selected')
				this.langSelected = element.get('id').split('_')[0];
			element.addEvent('click', function(e, element){
				this.editSwitchLang(element);
				e.stop();
			}.bindWithEvent(this, [element]))
		}.bind(this));
		$$('div.grey_wrapper_no_padding div.edit_form div.langs_form_wrapper').each(function(element, index){			
			if (element.get('id') == this.langSelected+'_form_wrapper')
				element.setStyle('display', 'block');
			else
				element.setStyle('display', 'none');
		}.bind(this));
		
		$$('input.autocomplete').each(function(element){
			var ac = new AutoComplete(element, {
				requestFieldName : 'Keyword',
				hiddenFieldClass: 'value_ac',
				urlAJAX : element.getSiblings('input.url_ac')[0].get('value')
			});
			element.store('AutoComplete', ac);
		});
		
		$$('select.bearer_autocomplete').each(function(element){
			var ac = new MultiAutoComplete(element, element.getSiblings('input.bearer_autocomplete')[0], {
				requestFieldName : 'Keyword',
				hiddenFieldClass: 'value_ac',
				urlAJAX : element.getSiblings('input.url_ac')[0].get('value')
			});
			element.store('AutoComplete', ac);
		});
	},
	
	editSwitchLang : function(element){
		var rel = element.get('id').split('_')[0];
		if (rel == this.langSelected)
			return false;
		$(rel+'_form_wrapper').setStyle('display', 'block');
		$(this.langSelected+'_form_wrapper').setStyle('display', 'none');
		$(this.langSelected+'_form_menu').set('class', '');
		$(rel+'_form_menu').set('class', 'selected');
		this.langSelected = rel;
	},
	
	initLogin : function(){
		
	},
	
	initOpenWrappers : function(){
		$$('a.open_wrapper_close').each(function(element, index){
			var id = element.get('id').split('_')[1];
			var h_calc = $('wrap_'+id).getFirst('div.h_calc');
			if ($chk($('wrap_'+id)) && $chk(h_calc)) {
				$('wrap_'+id).setStyles({
					'height' : '0px',
					'overflow' : 'hidden'
				});
				element.addEvent('click', function(e, id, h_calc){
					this.openWrapper(id, h_calc);
					e.stop();
				}.bindWithEvent(this, [id, h_calc]));
			}
		}.bind(this));
	},
	
	openWrapper : function(id, h_calc){
		var y = h_calc.getSize()['y'];
		var morph = new Fx.Morph($('wrap_'+id), {
			onComplete : function(){
				$('wrap_'+id).setStyles({
					'height' : 'auto',
					'overflow' : 'visible'
				});
				$('but_'+id).set('class', 'open_wrapper');
				$('but_'+id).removeEvents('click');
				$('but_'+id).addEvent('click', function(e, id, h_calc){
					this.closeWrapper(id, h_calc);
					e.stop();
				}.bindWithEvent(this, [id, h_calc]));
			}.bind(this)
		});
		morph.start({
			'height' : y.toString()+"px"
		});
	},
	
	closeWrapper : function(id, h_calc){
		var morph = new Fx.Morph($('wrap_'+id), {
			onStart : function(){
				$('wrap_'+id).setStyle('overflow', 'hidden');
			},
			onComplete : function(){
				$('but_'+id).set('class', 'open_wrapper_close');
				$('but_'+id).removeEvents('click');
				$('but_'+id).addEvent('click', function(e, id, h_calc){
					this.openWrapper(id, h_calc);
					e.stop();
				}.bindWithEvent(this, [id, h_calc]));
			}.bind(this)
		});
		morph.start({
			'height' : "0px"
		});
	},
	
	initGroupBySelect : function(){
		if (!$chk($('bo_listing_group_by')) || !$chk($('boForm')))
			return;
		//new Selects($('boForm'), $('bo_listing_group_by'));
	},
	
	initExportSelect : function(){
		if (!$chk($('listing_select_export')) || !$chk($('export_form')))
			return;
		
		new Selects($('export_form'), $('listing_select_export'),{
			'gap' : {
 					'left' : 80,  
 					'width': -80, 
 					'top'  : 25, 
 					'rTop': 0, 
 					'rLeft': 80 
			 	},
			 'onSelect' : function(element) {
			 		window.location = $('export_form').get('action')+'/Export_Type/'+element.get('href');
			 		Selects.elements['listing_select_export'].reset();
			 	}
		});
	},
	
	initListing : function(){
		var checkboxes = $$('table.listing input[type=checkbox]');
		$$('table.listing tr td').addEvent('click', function(e){
			var inputClicked = e.target.getParent('tr').getElement('input[type=checkbox]');
			var checked;
			if ($$('table.listing input.lastClicked').length == 1 && e.shift){
				var indexLast = checkboxes.indexOf($$('table.listing input.lastClicked')[0]);
				var indexNew = checkboxes.indexOf(inputClicked);
				
				var cb = checkboxes.filter(function(item, index){
					if ((index <= indexLast && index >= indexNew) || (index >= indexLast && index <= indexNew))
						return item;
				});
				
				if ((e.target.get('type') == 'checkbox' && checkboxes[indexNew].get('checked') == false) || (e.target.get('type') != 'checkbox' && checkboxes[indexNew].get('checked') == true))
					cb.set('checked', false);
				else
					cb.set('checked', true);
				checkboxes.removeClass('shifted');
				inputClicked.addClass('shifted');
			} 
			checkboxes.removeClass('lastClicked');
			inputClicked.addClass('lastClicked');
		});
		
		$$('table.listing tr.clear td, table.listing tr.dark td').each(function(element, index){
			var tr = element.getParent('tr');
			var check = tr.getFirst('td').getFirst('input');
			if (element.get('class') != 'check') {
				element.addEvent('click', function(e, element, tr, check){
					if (check.get('checked') == true && !check.hasClass('shifted')){
						check.set('checked', false);
						this.updateDeleteListing();
						this.updateEditListing();
						this.updateQuickEditListing();
						this.updateCloneListing();
						this.updateEmailListing();
					} else if (check.hasClass('shifted')) {
						check.removeClass('shifted');
					} else {
						check.set('checked', true);
						this.updateDeleteListing();
						this.updateEditListing();
						this.updateQuickEditListing();
						this.updateCloneListing();
						this.updateEmailListing();
					}
					e.stop();
				}.bindWithEvent(this, [element, tr, check]));
			}
			else {
				check.addEvent('change', function(){
					this.updateDeleteListing();
					this.updateEditListing();
					this.updateQuickEditListing();
					this.updateCloneListing();
					this.updateEmailListing();
				}.bind(this));
			}
		}.bind(this));
		
		$$('body')[0].addEvent('click', function(e){
			$$('div.rightclick_menu').destroy();
		});
		
		$$('table.listing td').addEvent('click', function(e){
			$$('div.rightclick_menu').destroy();
		});
		
		$$('table.listing td').addEvent('contextmenu', function(e){
			if (rights.add || rights.modify || rights.clone || rights.email || rights.del){
				e.stop();
				$$('div.rightclick_menu').destroy();
				
				var inputs = $$('table.listing tr td.check input.filter_checkbox');
				var ids = "";
				var nbIds = 1;
				
				ids += e.target.getParent('tr').getElement('input.filter_checkbox').get('id')+'|';
				
				for (var i=0;i<inputs.length;i++){
					if (inputs[i].get('checked') && !this.inArray(inputs[i].get('id'), ids.split('|'))){
						ids  += (i == inputs.length-1) ? inputs[i].get('id') : inputs[i].get('id')+'|';
						nbIds++;
					} 
				}

				if (e.target.getParent('tr').getElement('input.filter_checkbox').get('checked') == false)
					e.target.getParent('tr').getElement('input.filter_checkbox').set('checked', 'checked');
				
				ids = ids.substr(0, ids.length-1);
				
				var click_menu = new Element('div', {
					'class' : 'rightclick_menu',
					'events': {
						'contextmenu': function(e){
							if (e.rightClick){
								e.stop();
								this.destroy();
							}
						}
					}
				}).setStyles({
					'top' : e.page.y,
					'left' : e.page.x
				})
				.inject($$('body')[0]);
				
				var button_add = new Element('span', {
					'class' : 'add',
					'html' : slsBuild.langs.SLS_BO_LIST_ADD,
					'events': {
						'click' : function(){
							document.location = $$('ul.listing_actions a.add')[0].get('href');
						}
					}
				});
				
				var button_quick_add = new Element('span', {
					'class' : 'quick_add',
					'html' : slsBuild.langs.SLS_BO_LIST_QUICK_ADD,
					'events': {
						'click' : function(){
							Shadowbox.open({content: $$('ul.listing_actions a.quick_add')[0].get('href'), player: 'iframe'});
						}
					}
				});
				
				var button_modify = new Element('span', {
					'class' : 'modify',
					'html' : slsBuild.langs.SLS_BO_LIST_EDIT,
					'events': {
						'click' : function(){
							if (nbIds == 1)
								document.location = modify+ids+'.sls';
						}
					}
				});
				
				var button_quick_modify = new Element('span', {
					'class' : 'quick_modify',
					'html' : slsBuild.langs.SLS_BO_LIST_QUICK_EDIT,
					'events': {
						'click' : function(){
							if (nbIds == 1)
								Shadowbox.open({content: modify+ids+'/SlsQuick/iFrame'+'.sls', player: 'iframe'});
						}
					}
				});
				
				var button_clone = new Element('span', {
					'class' : 'clone',
					'html' : slsBuild.langs.SLS_BO_LIST_CLONE,
					'events': {
						'click' : function(){
							document.location = clone+ids+'.sls';
						}
					}
				});
				
				var button_email = new Element('span', {
					'class' : 'email',
					'html' : slsBuild.langs.SLS_BO_LIST_EMAIL,
					'events': {
						'click' : function(){
							document.location = email+ids+'.sls';
						}
					}
				});
				
				var button_delete = new Element('span', {
					'class' : 'delete',
					'html' : slsBuild.langs.SLS_BO_LIST_DELETE,
					'events': {
						'click' : function(){
							if (confirm("Etes-vous sûr de vouloir supprimer ces éléments?"))
								document.location = del+ids+'.sls';
						}
					}
				}).setStyle('border', 'none');
				
				if (rights.add) {
					button_add.inject(click_menu);
					button_quick_add.inject(click_menu);
				}
				if (nbIds <= 1 && rights.modify){
					button_modify.inject(click_menu);
					button_quick_modify.inject(click_menu);
				}
				if (rights.clone) button_clone.inject(click_menu);
				if (rights.email) button_email.inject(click_menu);
				if (rights.del) button_delete.inject(click_menu);
			}
			
			this.updateDeleteListing();
			this.updateEditListing();
			this.updateQuickEditListing();
			this.updateCloneListing();
			this.updateEmailListing();
		}.bind(this));
	},
	
	updateEditListing : function(){
		var inputs = $$('table.listing tr td.check input.filter_checkbox');
		var el = $$('ul.listing_actions .edit')[0];		
		var selected = 0;
		var id_selected = 0;		
		if ($chk(el)){
			for (var i=0;i<inputs.length;i++){
				if (inputs[i].get('checked')){
					selected++;
					id_selected = inputs[i].get('id');
				}
			}
			if (selected == 1){
				new Element('a', {
					'href' : modify+id_selected+'.sls',
					'class': 'edit',
					'html' : el.get('html')
				}).replaces(el);
			}
			else {
				new Element('span', {
					'class': 'edit',
					'html' : el.get('html')
				}).replaces(el);
			}
		}
	},
	
	updateQuickEditListing : function(){
		var inputs = $$('table.listing tr td.check input.filter_checkbox');
		var el = $$('ul.listing_actions .quick_edit')[0];		
		var selected = 0;
		var id_selected = 0;
		if ($chk(el)){
			for (var i=0;i<inputs.length;i++){
				if (inputs[i].get('checked')){
					selected++;
					id_selected = inputs[i].get('id');
				}
			}
			if (selected == 1){
				new Element('a', {
					'href' : modify+id_selected+'/SlsQuick/iFrame'+'.sls',
					'class': 'quick_edit',
					'rel': 'shadowbox',
					'html' : el.get('html')
				}).replaces(el);
				Shadowbox.setup("a.quick_edit");
			}
			else {
				new Element('span', {
					'class': 'quick_edit',
					'html' : el.get('html')
				}).replaces(el);
			}
		}
	},
	
	updateCloneListing : function(){
		var inputs = $$('table.listing tr td.check input.filter_checkbox');
		var el = $$('ul.listing_actions .clone')[0];
		var selected = 0;
		for (var i=0;i<inputs.length;i++){
			if (inputs[i].get('checked'))
				selected++;
		}
		if (selected > 0){
			new Element('a', {
				'href' : '',
				'class': 'clone',
				'html' : el.get('html'),
				'events': {
					'click' : function(e) {
						var inputs = $$('table.listing tr td.check input.filter_checkbox');
						var ids = "";
						for (var i=0;i<inputs.length;i++){
							if (inputs[i].get('checked')){
								ids  += inputs[i].get('id')+'|';
							}
						}
						window.location = clone+ids+'.sls';						
						e.stop();
					}
				}
			}).replaces(el);
		}
		else {
			new Element('span', {
				'class': 'clone',
				'html' : el.get('html')
			}).replaces(el);
		}
	},
	
	updateEmailListing : function(){
		var inputs = $$('table.listing tr td.check input.filter_checkbox');
		var el = $$('ul.listing_actions .email')[0];
		var selected = 0;
		for (var i=0;i<inputs.length;i++){
			if (inputs[i].get('checked'))
				selected++;
		}
		if (selected > 0){
			new Element('a', {
				'href' : '',
				'class': 'email',
				'html' : el.get('html'),
				'events': {
					'click' : function(e) {
						var inputs = $$('table.listing tr td.check input.filter_checkbox');
						var ids = "";
						for (var i=0;i<inputs.length;i++){
							if (inputs[i].get('checked')){
								ids  += inputs[i].get('id')+'|';
							}
						}
						window.location = email+ids+'.sls';						
						e.stop();
					}
				}
			}).replaces(el);
		}
		else {
			new Element('span', {
				'class': 'email',
				'html' : el.get('html')
			}).replaces(el);
		}
	},
	
	updateDeleteListing : function(){
		var inputs = $$('table.listing tr td.check input.filter_checkbox');
		var el = $$('ul.listing_actions .delete')[0];
		var selected = 0;
		for (var i=0;i<inputs.length;i++){
			if (inputs[i].get('checked'))
				selected++;
		}
		if (selected > 0){
			new Element('a', {
				'href' : '',
				'class': 'delete',
				'html' : el.get('html'),
				'events' : {
					'click' : function(e){
						var inputs = $$('table.listing tr td.check input.filter_checkbox');
						var ids = "";
						for (var i=0;i<inputs.length;i++){
							if (inputs[i].get('checked')){
								ids  += inputs[i].get('id')+'|';
							}
						}
						if (confirm(''+sls_confirm_msg)){
							window.location = del+ids+'.sls';
						}
						e.stop();
					}
				}
			}).replaces(el);
		}
		else {
			new Element('span', {
				'class': 'delete',
				'html' : el.get('html')
			}).replaces(el);
		}
	},
	
	inArray: function(needle, haystack) {
	    var length = haystack.length;
	    for(var i = 0; i < length; i++) {
	        if(haystack[i] == needle) return true;
	    }
	    return false;
	},
	
	quickIFrames: function(){
		if (window.Shadowbox){
			Shadowbox.options.onFinish = function(obj){
				var iframe = $(Shadowbox.player.id);
				var fkPage;
				
				iframe.addEvent('load', function(){
					if (this.contentWindow.page == 'listing'){
						var idAC = this.contentWindow.id_inserted;
						
						Shadowbox.close();
						if (page == 'listing'){
							var href = window.location.href;
							
							if (href.match(/SlsQuick\/Reload/g) != null){
								if (href.match(/SlsQuick\/ReloadAdd/g) != null)
									href = href.replace(/\/SlsQuick\/ReloadAdd/g, '');
								else if (href.match(/SlsQuick\/ReloadEdit/g) != null)
									href = href.replace(/\/SlsQuick\/ReloadEdit/g, '');
							}
							
							window.location = href.replace(/\.\w*$/g, '')+'/SlsQuick/Reload'+fkPage+href.match(/\.\w*$/g)[0];
							
						} else if (inputAC != null){
							var tick = inputAC.getSiblings('span[class*=autocomplete]')[0];
							tick.store('img', tick.getStyle('background-image'));
							
							new Request.JSON({
								url: inputAC.retrieve('url_ac').replace(/\.\w*$/g, '')+'/Id/'+idAC+inputAC.retrieve('url_ac').match(/\.\w*$/g)[0],
								method: 'get',
								onRequest: function(){
									tick.setStyles({
										'background-image' : 'url('+slsBuild.site.protocol+'://'+slsBuild.site.domainName+'/'+slsBuild.paths.coreIcons+'loading.gif'+')'
									});
								},
								onComplete: function(xhr){
									tick.setStyles({
										'background-image' : tick.retrieve('img')
									});
									
									if (inputAC.hasClass('autocomplete')){
										inputAC.set('value', xhr[0].label);
										inputAC.getSiblings('.value_ac')[0].set('value', xhr[0].id);
										inputAC.fireEvent('click');
										
									} else if (inputAC.hasClass('bearer_autocomplete')){
										var selectAC = inputAC.getSiblings('select.bearer_autocomplete')[0];
										
										// Select option
										var option = new Element('option', {
											'value' : xhr[0].id,
											'html' : xhr[0].label,
											'selected' : 'selected',
											'id' : (selectAC.getElements('option').length > 0) ? 'value_'+inputAC.get('id').match(/\d/)+'_'+(parseInt(selectAC.getElements('option').getLast().get('id').match(/\d+$/g))+1) : 'value_'+inputAC.get('id').match(/\d/)+'_'+0
										}).inject(selectAC);
										
										// AutoComplete tag
										var tag = new Element('div', {
											'id' : selectAC.getElements('option').getLast().get('id').replace(/value/, 'tag'),
											'class' : 'autocomplete_tag'
										}).inject(inputAC.getSiblings('div.tags')[0].getElement('div.clear'), 'before');
										
										var label = new Element('span', {
											'html' : xhr[0].label
										}).inject(tag);
										
										var remove = new Element('span', {
											'class' : 'autocomplete_tag_remove'
										}).inject(tag);									
										
									}
								}.bind(this)
							}).send();
						}
					} else {
						fkPage = this.contentWindow.fk_page.charAt(0).toUpperCase()+this.contentWindow.fk_page.slice(1);
					} 
				});
			}
		}
	}
	
});

var inputAC;

var AutoComplete = new Class({
	Implements: [Events, Options],
	
	ACopen : false,
	input : '',
	
	options: {
		urlAJAX : '',
		requestFieldName: '',
		hiddenFieldClass: '',
		responseDelay : 250,
		onSelect: function(){
			
		}
	},
	
	initialize: function(input, options){
		this.setOptions(options);
		this.input = input;
		
		
		if (this.options.requestFieldName == '')
			this.options.requestFieldName = this.input.get('name');
		
		this.buildACArea();
		this.buildInputEvents();
		
		if (window.location.href.match(/SlsQuick\/iFrame/g) == null){
			this.aAddFk = new Element('a', {
				'html' : slsBuild.langs.SLS_BO_LIST_QUICK_ADD,
				'href' : this.input.getSiblings('.url_add_fk')[0].get('value'),
				'rel'  : 'shadowbox',
				'class': 'ac_quick_link',
				'events': {
					click: function(){
						this.quickAdd();
					}.bind(this)
				}
			});
			
			Shadowbox.addCache(this.aAddFk);
		}
	},
	
	buildACArea: function(){
		this.input.addClass('ACInput'+$$('input[type=text]').indexOf(this.input)).set('autocomplete', 'off');
		
		this.ACwrapper = new Element('div', {
			'id' : 'ACInput'+$$('input[type=text]').indexOf(this.input),
			'class' : 'autocomplete_wrapper',
			'styles' : {
				'position' : 'absolute',
				'left' : this.input.getCoordinates().left,
				'background-color' : this.input.getStyle('background-color'),
				'display' : 'none'
			}
		}).inject(document.body);
		
		this.removeIcon = new Element('span', {
			'class' : 'autocomplete_remove',
			'events' : {
				click: function(){
					this.input.getSiblings('.'+this.options.hiddenFieldClass)[0].set('value', 0);
					this.input.set('value', '');
					this.input.focus();
					this.input.fireEvent('click');
				}.bind(this)
			}
		}).inject(this.input.getParent())
		this.removeIcon.store('img', this.removeIcon.getStyle('background-image'));
		
		$$('body')[0].addEvent('click', function(){
			this.closeAC();
			this.fireEvent("select");
		}.bind(this));
		
		window.addEvent('resize', function(){
			this.closeAC();
			this.ACwrapper.setStyles({
				'left' : this.input.getCoordinates().left
			});
		}.bind(this));
	},
	
	buildInputEvents: function(){
		this.input.store('value', this.input.getSiblings('.pattern_ac').get('value'));
		this.input.store('url_ac', this.options.urlAJAX);
		
		this.input.addEvents({
			click: function(){
				if (this.input.get('value') == '')
					this.sendRequest();
			}.bind(this),
			
			focus: function(){
				if (this.input.get('value') == this.input.retrieve('value'))
					this.input.set('value', '');
				this.input.setStyles({'background-color' : '#ffffff', 'color' : '#9F9F9F'});
			}.bind(this), 
			
			blur: function(){
				if (this.input.get('value') == '' || this.input.getSiblings('.value_ac').get('value') == 0){
					this.input.set('value', this.input.retrieve('value'));
					this.handleRemoveIcon();
				}
			}.bind(this),	
			
			keydown: function(e){
				if (e.key != 'up' && e.key != 'down' && e.key != 'enter'){
					$clear(this.timer);
					this.timer = this.sendRequest.delay(this.options.responseDelay, this);
				} else {
					e.stop();
					this.handleKeys(e.key);
				}
			}.bind(this)
		});
	},
	
	buildACResponse: function(xhr){
		this.ACwrapper.empty();
		xhr.each(function(element, index){
			var span = new Element('span', {
				'html' : element.label,
				'styles' : {
					'display' : 'block',
					'cursor' : 'pointer',
					'border-bottom-width' : (index == xhr.length-1) ? '0' : '1px'
				},
				'events' : {
					click: function(e){
						e.stop();
						this.input.getSiblings('.'+this.options.hiddenFieldClass)[0].set('value', span.retrieve('autocomplete_value'));
						this.input.set('value', span.innerHTML);
						this.closeAC();
						this.handleRemoveIcon();
						this.fireEvent('select');
					}.bind(this)
				}
			})
			.inject(this.ACwrapper)
			.store('autocomplete_value', element.id);
		}.bind(this));	
		
		if (this.aAddFk != null)
			this.aAddFk.inject(this.ACwrapper);
		
		if (xhr.length > 0){
			this.ACopen = true;
			this.ACwrapper.setStyles({
				'display' : 'block',
				'left' : this.input.getCoordinates().left,
				'min-width' : this.input.getCoordinates().width
			});
			
			this.ACwrapper.setStyles({
				'top' : ((this.ACwrapper.getChildren()[0].getCoordinates().height*xhr.length+this.input.getCoordinates().bottom) > (window.getScrollTop()+window.getHeight())) ? this.input.getCoordinates().top-this.ACwrapper.getCoordinates().height : this.input.getCoordinates().top+this.input.getCoordinates().height
			});
		}
	},
	
	sendRequest: function(){
		if (this.options.urlAJAX != ''){
			var urlPost = (this.input.get('value') == '') ? '' : '/'+this.options.requestFieldName+'/'+this.input.get('value');
			
			new Request.JSON({
				url : this.options.urlAJAX.replace(/\.\w*$/g, '')+urlPost+this.options.urlAJAX.match(/\.\w*$/g)[0],
				method: 'get',
				onRequest: function(){
					this.loading();
				}.bind(this),
				onComplete: function(xhr){
					this.buildACResponse(xhr);
					this.handleRemoveIcon();
				}.bind(this)
			}).send();
		}
	},
	
	handleKeys: function(key){
		if (key == 'enter' && this.ACwrapper.getElements('.hover').length > 0){
			var element = this.ACwrapper.getElement('.hover');
			
			if (element.hasClass('ac_quick_link')){
				this.quickAdd();
				Shadowbox.open(this.aAddFk);
			} else {
				this.input.set('value', element.innerHTML);
				this.input.getSiblings('.value_ac')[0].set('value', element.retrieve('autocomplete_value'));
				this.handleRemoveIcon();
				this.fireEvent('select');
			}
			this.closeAC();
		} else {
			var index;
			if (this.ACwrapper.getElements('.hover').length == 0){
				if (key == 'up')
					index = this.ACwrapper.getChildren().length-1;
				else 
					index = 0;
			} else {
				var indexLast = this.ACwrapper.getChildren().indexOf(this.ACwrapper.getElement('.hover'));
				this.ACwrapper.getElement('.hover').removeClass('hover');
				if (key == 'up')
					index = (indexLast-1 == -1) ? this.ACwrapper.getChildren().length-1 : (indexLast-1)%this.ACwrapper.getChildren().length;
				else
					index = (indexLast+1)%this.ACwrapper.getChildren().length;
			}
			this.ACwrapper.getChildren()[index].addClass('hover');
		}
	},
	
	closeAC: function(){
		this.ACopen = false;
		this.ACwrapper.empty()
		.setStyle('display', 'none');
	},
	
	handleRemoveIcon: function(){
		this.removeIcon.setStyles({'background-image' : this.removeIcon.retrieve('img')});
		if (this.input.get('value') != 0)
			this.removeIcon.setStyles({'display' : 'block'});
		else
			this.removeIcon.setStyles({'display' : 'none'});
	},

	loading: function(){
		this.removeIcon.setStyles({'display' : 'block', 'background-image' : 'url('+slsBuild.site.protocol+'://'+slsBuild.site.domainName+'/'+slsBuild.paths.coreIcons+'loading.gif'+')'});
	},
	
	quickAdd: function(){
		inputAC = this.input;
	}
});

var MultiAutoComplete = new Class({
	Implements: [Events, Options],
	
	options: {
		urlAJAX : '',
		requestFieldName: '',
		hiddenFieldClass: '',
		responseDelay : 250
	},
	
	initialize: function(select, input, options){
		this.setOptions(options);
		this.select = select;
		this.input = input;
		
		if (this.options.requestFieldName == '')
			this.options.requestFieldName = this.input.get('name');
		
		this.buildACArea();
		this.buildInputEvents();
		this.buildTagEvents();
		
		if (window.location.href.match(/SlsQuick\/iFrame/g) == null){
			this.aAddFk = new Element('a', {
				'html' : slsBuild.langs.SLS_BO_LIST_QUICK_ADD,
				'href' : this.input.getSiblings('.url_add_fk')[0].get('value'),
				'rel'  : 'shadowbox',
				'class': 'ac_quick_link',
				'events': {
					click: function(){
						this.quickAdd();
					}.bind(this)
				}
			});
			
			Shadowbox.addCache(this.aAddFk);
		}
	},
	
	buildACArea: function(){
		this.ACwrapper = new Element('div', {
			'id' : 'ACInput'+$$('input[type=text]').indexOf(this.input),
			'class' : 'autocomplete_wrapper',
			'styles' : {
				'position' : 'absolute',
				'left' : this.input.getCoordinates().left,
				'background-color' : this.input.getStyle('background-color'),
				'display' : 'none'
			}
		}).inject(document.body);
		
		this.removeIcon = new Element('span', {
			'class' : 'bearer_autocomplete_add',
			'events' : {
				click: function(){
					this.input.set('value', '');
					this.input.focus();
					this.input.fireEvent('click');
				}.bind(this)
			}
		}).inject(this.input, 'after')
		this.removeIcon.store('img', this.removeIcon.getStyle('background-image'));
		
		$$('body')[0].addEvent('click', function(){
			this.closeAC();
		}.bind(this));
		
		window.addEvent('resize', function(){
			this.closeAC();
			this.ACwrapper.setStyles({
				'left' : this.input.getCoordinates().left
			});
		}.bind(this));
	},
	
	buildInputEvents: function(){
		this.input.store('value', this.input.getSiblings('.pattern_ac').get('value'));
		this.input.store('url_ac', this.options.urlAJAX);
		
		this.input.addEvents({
			click: function(){
				if (this.input.get('value') == '')
					this.sendRequest();
			}.bind(this),
			
			focus: function(){
				if (this.input.get('value') == this.input.retrieve('value'))
					this.input.set('value', '');
			}.bind(this), 
			
			blur: function(){
				if (this.input.get('value') == '' || this.input.getSiblings('.value_ac').get('value') == 0){
					this.input.set('value', this.input.retrieve('value'));
					this.handleRemoveIcon();
				}
			}.bind(this),	
			
			keydown: function(e){
				if (e.key != 'up' && e.key != 'down' && e.key != 'enter'){
					$clear(this.timer);
					this.timer = this.sendRequest.delay(this.options.responseDelay, this);
				} else {
					e.stop();
					this.handleKeys(e.key);
				}
			}.bind(this)
		});
	},
	
	buildTagEvents: function(){
		this.select.getSiblings('div.tags')[0].addEvent('click:relay(span.autocomplete_tag_remove)', function(e){
			this.removeTag(e.target.getParent().get('id'));
		}.bind(this));
	},
	
	sendRequest: function(){
		if (this.options.urlAJAX != ''){
			var urlPost = (this.input.get('value') == '') ? '' : '/'+this.options.requestFieldName+'/'+this.input.get('value');
			
			new Request.JSON({
				url : this.options.urlAJAX.replace(/\.\w*$/g, '')+urlPost+this.options.urlAJAX.match(/\.\w*$/g)[0],
				method: 'get',
				onRequest: function(){
					this.loading();
				}.bind(this),
				onComplete: function(xhr){
					this.buildACResponse(xhr);
					this.handleRemoveIcon();
				}.bind(this)
			}).send();
		}
	},
	
	handleKeys: function(key){
		if (key == 'enter' && this.ACwrapper.getElements('.hover').length > 0){
			
			var element = this.ACwrapper.getElement('.hover');
			
			if (element.hasClass('ac_quick_link')){
				this.quickAdd();
				Shadowbox.open(this.aAddFk);
			} else {
				this.addValue(element.retrieve('autocomplete_value'), element.get('html'));
				this.input.set('value', '');
				this.input.blur();
				this.handleRemoveIcon();
			}
			this.closeAC();
		} else {
			var index;
			if (this.ACwrapper.getElements('.hover').length == 0){
				if (key == 'up')
					index = this.ACwrapper.getChildren().length-1;
				else 
					index = 0;
			} else {
				var indexLast = this.ACwrapper.getChildren().indexOf(this.ACwrapper.getElement('.hover'));
				this.ACwrapper.getElement('.hover').removeClass('hover');
				if (key == 'up')
					index = (indexLast-1 == -1) ? this.ACwrapper.getChildren().length-1 : (indexLast-1)%this.ACwrapper.getChildren().length;
				else
					index = (indexLast+1)%this.ACwrapper.getChildren().length;
			}
			this.ACwrapper.getChildren()[index].addClass('hover');
		}
	},
	
	buildACResponse: function(xhr){
		this.ACwrapper.empty();
		xhr.each(function(element, index){
			var span = new Element('span', {
				'html' : element.label,
				'styles' : {
					'display' : 'block',
					'cursor' : 'pointer',
					'border-bottom-width' : (index == xhr.length-1) ? '0' : '1px'
				},
				'events' : {
					click: function(e){
						e.stop();
						this.addValue(span.retrieve('autocomplete_value'), span.get('html'));
						this.input.set('value', this.input.retrieve('value'));
						this.closeAC();
						this.handleRemoveIcon();
					}.bind(this)
				}
			})
			.inject(this.ACwrapper)
			.store('autocomplete_value', element.id);
		}.bind(this));		
		
		if (this.aAddFk != null)
			this.aAddFk.inject(this.ACwrapper);
		
		if (xhr.length > 0){
			this.ACwrapper.setStyles({
				'display' : 'block',
				'left' : this.input.getCoordinates().left,
				'min-width' : this.input.getCoordinates().width
			});
			
			this.ACwrapper.setStyles({
				'top' : ((this.ACwrapper.getChildren()[0].getCoordinates().height*(xhr.length+1)+this.input.getCoordinates().bottom) > (window.getScrollTop()+window.getHeight())) ? this.input.getCoordinates().top-this.ACwrapper.getCoordinates().height : this.input.getCoordinates().top+this.input.getCoordinates().height
			});
		}
	},
	
	addValue: function(id, label){
		if (this.select.getElements('option[value='+id+']').length == 0){
			var option = new Element('option', {
				'value' : id,
				'html' : label,
				'selected' : 'selected',
				'id' : (this.select.getElements('option').length > 0) ? 'value_'+this.input.get('id').match(/\d/)+'_'+(parseInt(this.select.getElements('option').getLast().get('id').match(/\d+$/g))+1) : 'value_'+this.input.get('id').match(/\d/)+'_'+0
			}).inject(this.select);
			
			this.newTag(label);
		}
	},
	
	newTag: function(value){
		var tag = new Element('div', {
			'id' : this.select.getElements('option').getLast().get('id').replace(/value/, 'tag'),
			'class' : 'autocomplete_tag'
		}).inject(this.input.getSiblings('div.tags')[0].getElement('div.clear'), 'before');
		
		var label = new Element('span', {
			'html' : value
		}).inject(tag);
		
		var remove = new Element('span', {
			'class' : 'autocomplete_tag_remove',
			'events' : {
				click: function(){
					this.removeTag(tag.get('id'));
				}.bind(this)
			}
		}).inject(tag);
	},
	
	removeTag: function(id){
		$(id).destroy();
		this.select.getElement('option[id='+id.replace(/tag/, 'value')+']').destroy();
	},
	
	closeAC: function(){
		this.ACwrapper.empty()
		.setStyle('display', 'none');
	},
	
	handleRemoveIcon: function(){
		this.removeIcon.setStyles({'background-image' : this.removeIcon.retrieve('img')});
		if (this.input.get('value') != 0)
			this.removeIcon.setStyles({'display' : 'block'});
		else
			this.removeIcon.setStyles({'display' : 'none'});
	},

	loading: function(){
		this.removeIcon.setStyles({'display' : 'block', 'background-image' : 'url('+slsBuild.site.protocol+'://'+slsBuild.site.domainName+'/'+slsBuild.paths.coreIcons+'loading.gif'+')'});
	},
	
	quickAdd: function(){
		inputAC = this.input;
	}
});